package com.caiyi.financial.nirvana.sms.aspect;


import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.caiyi.financial.nirvana.sms.entity.SmsAdmin;
import com.caiyi.financial.nirvana.sms.entity.SmsLog;
import com.caiyi.financial.nirvana.sms.mapper.SmsLogMapper;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.subject.Subject;
import org.aspectj.lang.JoinPoint;
import org.aspectj.lang.annotation.AfterReturning;
import org.aspectj.lang.annotation.Aspect;
import org.aspectj.lang.annotation.Pointcut;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.http.HttpServletRequest;

@Aspect
@Component
public class AddOperateLogAspect {
    private Logger logger = LoggerFactory.getLogger(this.getClass());
    @Autowired
    private HttpServletRequest request;
    @Autowired
    private SmsLogMapper logMapper;

    @Pointcut(value = "execution(* com.caiyi.financial.nirvana.sms.service.*.add*(..))")
    public void pointCutMethod() {
    }

    @AfterReturning(pointcut = "pointCutMethod()", returning = "result")
    public void doAfterReturning(JoinPoint joinPoint, Object result) {
        try {
            SmsLog log = new SmsLog();
            Subject subject = SecurityUtils.getSubject();
            SmsAdmin admin = (SmsAdmin) subject.getPrincipal();
            log.setAccount(admin.getAccount());
            log.setIp(request.getRemoteAddr());
            String methodName = joinPoint.getSignature().getName();
            log.setMethod(methodName);
            log.setType(1);
            String parameter = JSON.toJSONString(joinPoint.getArgs());
            log.setParameter(parameter);
            log.setResponse(JSONObject.toJSONString(result));
            logMapper.insertSelective(log);
        } catch (Exception e) {
            logger.error("add log operate...", e);
        }
    }
}
